import { Injectable } from '@nestjs/common';
import { CreateCategoryDto } from './dto/create-category.dto';
import { UpdateCategoryDto } from './dto/update-category.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Category } from './entities/category.entity';
import { Repository } from 'typeorm';
import { getPageResult } from 'src/utils';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private categoryRepository: Repository<Category>
  ) {}
  async create(createCategoryDto: CreateCategoryDto) {
    return await this.categoryRepository.insert(createCategoryDto);
  }
  // 获取图书分类列表
  async findAll() {
    return await this.categoryRepository.find({
      select: {
        create_time: false,
        update_time: false,
      }
    })
  }
  // 获取图书分类分页列表
  async findPageList({pageIndex, pageSize, category_name}) {
    let queryBuilder = this.categoryRepository.createQueryBuilder()
    .select('*')
    if(category_name) {
      queryBuilder = queryBuilder
      .where('category_name LIKE :category_name', { category_name: `%${category_name}%`})
    }
    return await getPageResult(pageIndex, pageSize, queryBuilder)
  }
  // 分类详情
  async findOne(id: number) {
    return await this.categoryRepository.findOne({where: {id}})
  }
  // 修改分类
  async update(id: number, updateCategoryDto: UpdateCategoryDto) {
    return await this.categoryRepository.update(id, updateCategoryDto);
  }
  // 删除分类
  async remove(id: number) {
    return await this.categoryRepository.softDelete(id);
  }
}
